<?php
/**
 * Trida slouzi pro komunikaci s api RealStudia.
 *
 * @author David Dusek
 */
class DataRequest {
    /*
     * konstanty pro jednotlive pozadavky na API
     */
    public static $pathAffiliate = "GetAffiliate";
    public static $pathAffiliateIdList = "GetAffiliateIdList";
    public static $pathAgent = "GetAgent";
    public static $pathAgentIdList = "GetAgentIdList";
    public static $pathEstate = "GetEstate";
    public static $pathEstateIdList = "GetEstateIdList";
    public static $pathFileData = "GetFileData";
    
    /**
     * Login do API
     * @var String 
     */
    public static $login = "vaseR";
    /**
     * Heslo do API
     * @var String 
     */
    public static $password = "vsrx.?89KR2p";
    
    /**
     * cesta k API
     * @var String 
     */
    public static $path = "/datapublisher.asmx/";
    /**
     * Adresa hostilele API
     * @var String 
     */
    public static $host = "datapublisher.realsw.cz";
    
    /**
     * Odesle POST pozadavek na API datapublisheru. Typo pozadavku je dan 
     * parametrem requestType kde je jeden z retezcu z pathxxx. Vysledne XML od
     * API je ulozeno do atributu XMLString.
     * @param array $parametrs potrebna data pro pozadavek (login, heslo a pripadne 
     * id)
     * @param String $requestType typ pozadavku
     * @return String XML odpoved od API
     */
    public function sendRequest($parametrs, $requestType) {
        $result = '';
        $data = urldecode(http_build_query($parametrs, null, "&"));
        $size = strlen($data);

        $fp = fsockopen(DataRequest::$host,80, $errno, $erresulttr, 30);

        if($fp) {
            $request = "POST " . DataRequest::$path . $requestType . " HTTP/1.1\r\n";
            $request.= "Host: " . DataRequest::$host . "\r\n";
            $request.= "Content-Type: application/x-www-form-urlencoded\r\n";
            $request.= "Content-Length: ".$size."\r\n\r\n";
            $request.= $data . "\r\n";
            $request.= "Connection: Closer\r\n\r\n";
            
            fwrite($fp, $request);

            while(!feof($fp)) {
                $result .= fgets($fp, 128);	
            }	
        } else {
            $error = "$erresulttr ($errno)";
        } 

        fclose($fp);

        // rozdel na hlavicku od tela odpovedi
        list($header, $content) = explode("\r\n\r\n", $result, 2);
        // oddel telo od chyboveho hlaseni 400 ivalid verb
        list($content, $error) = explode("HTTP/1.1 400 Bad Request", $content, 2);
        
        return $content;
    }    
}
